// pages/facilityDetail/facilityDetail.js
var app=getApp();
var mta = require('../../../utils/mta_analysis.js');
var isseue_timer;
var ISSUE_TIME = 300;
var issue_time=ISSUE_TIME,issue_falg=false;
var is_can=true;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    equipments_num:'../../../images/equipments_num.png',
    equipments_time: '../../../images/equipments_time.png',
    open:false,//开关
    openfirst:true,//防止频繁点击
    screen:false,//显屏
    screenfirst:true,//防止频繁点击
    is_number:false,//绑定设备数量，大于1为true，小于等于1则为flase
    equipment_id:'',
    device_no:'',
    info:{},
    isShare:true,
    forced_flushing_time:0,
    showmove:true,
    showclick:true,
    wash_regularly: 2,//定时冲洗，单位h，默认2
    screen_mode: 1,//1：已用天数、已用流量，2：已用天数、剩余流量，3：剩余天数、已用流量，4：剩余天数、剩余流量'
    screenList:[],//显示配置
    timedFlList:[],//冲洗配置
    top: app.globalData._network_path + 'flow1.png',
    mid: app.globalData._network_path + 'flow2.png',
    bot: app.globalData._network_path + 'flow3.png',
    is_load:false,
    working_mode:1,
    filter_element_max:[],
    is_send:0,
    tips_text:'',//弹窗提示语
    maintenance_state_switching_btn:false,//解除检修按钮是否显示
    data_sync:false,//数据同步按钮是否显示
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    mta.Page.init();
    var is_move=wx.getStorageSync('is_move');
    var is_click = wx.getStorageSync('is_click');
    that.setData({
      equipment_id: options.equipment_id
    })
    //that.bindNum();
    that.equipmentDetail();
    if (is_move == '' || is_move == undefined || is_move==null){
      that.setData({
        showmove: false
      })
    }

  },
  onShow: function () {
    var that=this;
    that.screenMode();//获取屏显模式配置
  },
  /**
    * 页面相关事件处理函数--监听用户下拉动作
    */
  onPullDownRefresh: function () {
    var that = this;
    that.equipmentDetail();
  },
  /**
   * 设备详情
   */
  equipmentDetail:function(){
    var that = this;
    var equipment_id = that.data.equipment_id;
    app.ajax({
      url:"Engineer/Equipmentlists/equipmentDetail",
      data: { "equipment_id": equipment_id},
      success:function(res){
          wx.stopPullDownRefresh()
          if(res.data.code==1000){
            var maintenance_state_switching_btn = false;
            var data_sync = false;
            //如果是检修状态
            if(res.data.data.repair_state==1){
                maintenance_state_switching_btn = true;
            }
            //如果是欠费状态
            if(res.data.data.device_status==3){
              data_sync = true;
            }
            that.setData({
              info:res.data.data,
              open: res.data.data.switch_machine == 0 ? false : true,
              screen: res.data.data.screen_status == 0 ? true : false,
              device_no: res.data.data.device_no,
              equipment_id: res.data.data.equipment_id,
              wash_regularly: res.data.data.wash_regularly == 0 ? 2 : res.data.data.wash_regularly,
              screen_mode: res.data.data.screen_mode,
              maintenance_state_switching_btn:maintenance_state_switching_btn,
              data_sync:data_sync
            })
          }
        that.timedFlush(res.data.data.wash_regularly);//获取定时冲洗配置
        that.setData({
          is_load:true
        })
      }
    })
  },
  /**
   * 获取用户绑定的设备
   */
  bindNum:function(){
    var that = this;
    app.ajax({
      url: 'User/Equipmentlists/bindNum',
      data: { },
      success: function (res) {
        if (res.data.code == 1000) {
          //获取设备数量
          if(res.data.data.count > 1){
            that.setData({
              is_number:true
            });
          }
        } else {
          // console.log(res.data);
          //没有绑定设备
        }

      }
    })
  },
  addDevice:function(){
    wx.navigateTo({
      url: '../addEquipment/addEquipment',
    })
  },
  
  //用水量
  columnChart(e){
    var that=this;
    var id = e.currentTarget.dataset.id;
    that.setData({
      showclick: true
    })
    wx.setStorageSync('is_click', true);
      wx.navigateTo({
        url: '../columnChart/columnChart?equipment_id='+id,
      })
      
},
  //选择设备
  chooseFacility(){
      wx.switchTab({
        url: '../home/home',
      })
  },
  //选择
  facilityInformation(e){
    var parts_id = e.currentTarget.dataset.parts_id;
    var equipment_id = e.currentTarget.dataset.equipment_id;
    var id = e.currentTarget.dataset.id;
    var index = e.currentTarget.dataset.index;
    wx.navigateTo({
      url: '../facilityInformation/facilityInformation?parts_id=' + parts_id + "&equipment_id=" + equipment_id + "&id=" + id + "&index=" + index,
    })
  },
  //开关
  chooseone(e){
    var that = this, opes = e.currentTarget.dataset.types, openfirst = that.data.openfirst;
    var type = that.data.info.type;
    var status = that.data.info.status;    
    if (type != 1) {
      app.showToast("您的设备非智能设备无法使用该功能", 'none', 2500);
      return false;
    }
    if (status == 1) {
      app.showToast("您的设备已离线，无法进行该操作", 'none', 2500);
      return false;
    }
    if (openfirst == false) {
      app.showToast("为保护设备请勿频繁操作,请5秒后重试", 'none', 3000);
      return false;
    }
    if (opes == false) {
      that.powerOff(0)
      that.setData({
        open: true,
        openfirst:false,
      })
    } else {
      that.powerOff(1)
      that.setData({
        open: false,
        openfirst: false,
      })
    }
  },
  //冲洗
  choosetwo(e){
    // app.showToast("冲洗成功",'none',2500);
    var that = this;
    var sn = that.data.device_no;
    var type = that.data.info.type;
    var status = that.data.info.status;
    if (type != 1) {
      app.showToast("您的设备非智能设备无法使用该功能", 'none', 2500);
      return false;
    }
    if(status == 1){
      app.showToast("您的设备已离线，无法进行该操作", 'none', 2500);    
      return false;  
    }
    if (!that.data.open) {
      app.showToast("请先开启设备", 'none', 2500);
      return false;
    }
    app.ajax({
      url: 'House/Issue/mandatory_rinse',
      data: { "sn": sn },
      success: function (res) {
        var forced_flushing_time = that.data.info.forced_flushing_time;
        that.setData({
          forced_flushing_time: forced_flushing_time,
          isShare: false
        })
        wx.vibrateLong();
        var timer = setInterval(function(){
          
          forced_flushing_time--;
          that.setData({
            forced_flushing_time: forced_flushing_time
          })
          if (forced_flushing_time<=0){
            clearInterval(timer);
            that.setData({
              isShare: true,
              forced_flushing_time:0
            })
            app.showToast('亲,您的设备已经干净了~', 'none', 2500);
          }
          //console.log(forced_flushing_time)
        },1000)
      }
    })
  },
  //显屏
  choosethree(e){
    var that = this, sceend = e.currentTarget.dataset.types, screenfirst = that.data.screenfirst;
    var type = that.data.info.type;
    var status = that.data.info.status;    
    if (type != 1) {
      app.showToast("您的设备非智能设备无法使用该功能", 'none', 2500);
      return false;
    }
    if (status == 1) {
      app.showToast("您的设备已离线，无法进行该操作", 'none', 2500);
      return false;
    }
    if (!that.data.open) {
      app.showToast("请先开启设备", 'none', 2500);
      return false;
    }    
    if (screenfirst == false) {
      app.showToast("为保护设备请勿频繁操作,请5秒后重试", 'none', 3000);
      return false;
    }
    if (sceend == false) {
      that.screen_status(0)
      that.setData({
        screen: true,
        screenfirst: false,
      })
    } else {
      that.screen_status(1)
      that.setData({
        screen: false,
        screenfirst: false,
      })
    }
  },
  //下发屏幕开关
  screen_status(screen_status) {
    var that = this;
    var screen_status = screen_status;
    var sn = that.data.device_no;
    app.ajax({
      url: 'House/Issue/screen_status',
      data: { "sn": sn, "screen_status": screen_status },
      success: function (res) {
        var msg;
        if (screen_status == 0){
          msg = '设备屏显已开启';
        }else{
          msg = '设备屏显已关闭';
        }
        wx.vibrateLong();
        app.showToast(msg, 'none', 2500);
        setTimeout(() => {
          that.setData({
            screenfirst: true
          })
        }, 5000);
      }
    })
  },
  //发送指令
  //开关机
  powerOff(device_status) {
    var that = this;
    var device_status = device_status;
    var sn = that.data.device_no;
    app.ajax({
      url: 'House/Issue/power_off',
      data: { "sn": sn, "device_status": device_status },
      success: function (res) {
        var msg;
        if (device_status == 0) {
          msg = '设备已开启';
        } else {
          msg = '设备已关闭';
        }
        wx.vibrateLong();
        app.showToast(msg, 'none', 2500);
        setTimeout(() => {
          that.setData({
            openfirst: true
          })
        }, 5000);
        return false;
        }
      
    })
  },
  //续费
  goRenew: function (e) {
    var contract_id = e.currentTarget.dataset.contract_id;
    wx.navigateTo({
      url: '../user/renew/renew?contract_id=' + contract_id,
    })
  },
  //复制设备编号
  copyDeviceNo: function(e){
    var dev = e.currentTarget.dataset.dev;
    console.log(dev);
    wx.setClipboardData({
      data: dev,
      success: function (res) {
        wx.getClipboardData({
          success: function (res) {
            console.log(res.data) // data
          }
        })
      }
    })
  },
  //距离左边
  scrollLeft(e) {
    var that = this;
    if (e.detail.scrollLeft > 12) {
      that.setData({
        showmove: true
      })
      wx.setStorageSync('is_move', true);
    }
  },
  //客服
  helpCenter() {
    wx.navigateTo({
      url: '../customService/customService',
    })
  },
  //申请售后
  applyAfterSale: function (e) {
    //console.log();
    var device_no = e.currentTarget.dataset.device_no;
    var equipment_id = e.currentTarget.dataset.equipment_id;
    wx.navigateTo({
      url: '../user/applyAfterSale/applyAfterSale?device_no=' + device_no + '&equipment_id=' + equipment_id,
    })
  },
  //解绑
  flDetele(e) {
    var that = this, equipment_id = e.currentTarget.dataset.equipment_id;
    wx.showModal({
      title: '是否解绑',
      content: '解绑之后将无法查看该设备信息',
      showCancel: true,
      cancelText: '算了吧',
      cancelColor: '#6CA9FF',
      confirmText: '解绑',
      confirmColor: '#FF9E7D',
      success: function (res) {
        //确定事件
        if (res.confirm == true) {
          app.ajax({
            url: 'User/Equipmentlists/unBindEquipment',
            data: { "equipment_id": equipment_id },
            success: function (res) {
              if (res.data.code == 1000) {
                // var equipment = that.data.equipment;
                // if (equipment.length == 2) {
                //   that.setData({
                //     equipment_num: 0,
                //     is_delete: true
                //   })
                // }
                //that.userBindEquipment();//重新调取接口
                app.showToast('删除成功');
                wx.navigateBack({
                  delta: 1
                })
              } else {
                app.showToast(res.data.message);
              }
            }
          })
          //that.handlePoster();
        }
        //取消事件
        if (res.cancel == true) {
          // app.showToast('取消了就没办法分享给好友了')
        }
      },
    })
  },
  //定时冲洗
  choosefour(e){
    var that = this, sn = that.data.device_no,
     index = e.currentTarget.dataset.index;
    var type = that.data.info.type;
    var status = that.data.info.status;
    if (type != 1) {
      app.showToast("您的设备非智能设备无法使用该功能", 'none', 2500);
      return false;
    }
    if (status == 1) {
      app.showToast("您的设备已离线，无法进行该操作", 'none', 2500);
      return false;
    }
    if (!that.data.open) {
      app.showToast("请先开启设备", 'none', 2500);
      return false;
    }
    var timedFlList = that.data.timedFlList;
    if ((index+1) < timedFlList.length){
        index += 1;
      }else{
        index = 0;
      }
    //console.log('index', index, 'length', timedFlList.length, "这是谁?", timedFlList[index].value)
      app.ajax({
        url: "House/Issue/modified_timed_washing",
        data: { sn: sn, value: timedFlList[index].value},
        success: function (res) {
          if (res.data.code == 1000) {
            app.showToast(parseInt(timedFlList[index].value)+'小时冲洗一次', 'none', 2500);
            that.setData({
              wash_regularly: timedFlList[index].value
            })
          }else{
            app.showToast(res.data.message, 'none', 2500);
          }
        }
      })
  },
  //切换屏显
  choosefive(e){
    var that = this, sn = that.data.device_no,index = e.currentTarget.dataset.index;
    var type = that.data.info.type;
    var status = that.data.info.status;
    if (type != 1) {
      app.showToast("您的设备非智能设备无法使用该功能", 'none', 2500);
      return false;
    }
    if (status == 1) {
      app.showToast("您的设备已离线，无法进行该操作", 'none', 2500);
      return false;
    }
    if (!that.data.open) {
      app.showToast("请先开启设备", 'none', 2500);
      return false;
    }
    var screenList = that.data.screenList;
    if (index < screenList.length) {
      index += 1;
    } else {
      index = 1;
    }
    //console.log('index', index, 'length', screenList.length, "上传的结果?", screenList[index-1].time_mode,screenList[index-1].flow_mode)
    app.ajax({
      url: "House/Issue/switch_screen_display_mode",
      data: { sn: sn, value: [screenList[index-1].time_mode, screenList[index-1].flow_mode]},
      success: function (res) {
        if (res.data.code == 1000) {
          app.showToast('模式' + ' ' +screenList[index - 1].description , 'none', 3000);
          that.setData({
            screen_mode: index
          })
        } else {
          app.showToast(res.data.message, 'none', 2500);
        }
      }
    })
 
  },
  //获取屏显模式配置  
  screenMode(){
    var that=this;
    app.ajax({
      url: "Common/Conf/screenMode",
      data: {},
      success: function (res) {
        if (res.data.code == 1000) {
          that.setData({
            screenList: res.data.data
          })
        }
      }
    })
  },
  //获取定时冲洗配置
  timedFlush(wash_reguss) {
    var that = this;
    app.ajax({
      url: "Common/Conf/timedFlush",
      data: {},
      success: function (res) {
        if (res.data.code == 1000) {
          var havValue = false, arrshow = res.data.data;
          for (var i = 0; i < arrshow.length; i++) {
            if (arrshow[i].value == wash_reguss) {
              havValue = true;
            }
          }
          var obj = { 'description': wash_reguss + '小时冲洗一次', 'value': wash_reguss };
          if (!havValue) {
            arrshow.push(obj);
          }
          that.setData({
            timedFlList: arrshow
          })
        }
      }
    })
  },
  //重新下发套餐
  IssuePackage(){
    var that = this;
    clearInterval(isseue_timer);
    if (issue_falg && issue_time>0){
      app.showToast("请不要频繁下发套餐," + ISSUE_TIME/60+"分钟后再重新下发");
      return false;
    }
    app.showModal("","是否需要重新下发套餐??",function(){
      issue_falg= true
      that.issue(that.data.info.device_no);
    })
  },

  tapIssue(){
    this.issue(); 
  },

  //下发套餐接口
  issue(device_no=""){
    
    var that = this;
    const num = device_no == "" ? that.data.device_no : device_no;
    if (!is_can){
      app.showToast('套餐下发中，请勿频繁操作！');
      return false
    }
    is_can=false
    that.setData({
      is_send: 1,
      tips_text: '套餐下发中,请耐心等待'
    })
    app.ajax({
      url: "Common/Contract/issuePackage",
      data: { device_no: num },
      success: function (res) {
        that.syncRedisToDevice();
      //  app.showToast(res.data.message);
       if(res.data.code==1000){
         that.setData({
           is_send: 1,
           tips_text:'套餐下发成功！由于网络原因可能导致数据未更新请多次尝试'
         })
         
        
       }else{
         that.setData({
           is_send: 1,
           tips_text: '套餐下发失败,请重试'
         })
       }
        setTimeout(() => {
          that.setData({
            is_send: 0
          })
          that.equipmentDetail();
        }, 2000)
       setTimeout(()=>{
         is_can=true
       },2000)
      }
    })
  },

  //同步滤芯
  SyncFilter(){
    var that = this;
    var equipment_id = that.data.equipment_id;
    if (!is_can) {
      console.log('阻止')
      app.showToast('滤芯数据同步中，请勿频繁操作！');
      return false
    }
    is_can = false
    that.setData({
      is_send: 1,
      tips_text: '滤芯数据同步中,请耐心等待'
    })
    app.ajax({
      url: "Common/Device/syncFilterData",
      data: { equipment_id: equipment_id },
      success: function (res) {
        that.syncRedisToDevice();
        //  app.showToast(res.data.message);
        if (res.data.code == 1000) {
          that.setData({
            is_send: 2,
            tips_text: '滤芯数据同步成功！由于网络原因可能导致数据未更新请多次尝试'
          })
         
        } else {
          that.setData({
            is_send: 2,
            tips_text: '滤芯数据同步失败,请重试'
          })
        }
        setTimeout(() => {
          that.setData({
            is_send: 0
          })
          that.equipmentDetail();
        }, 2000)
        setTimeout(() => {
          is_can = true
        }, 2000)
      }
    })
    
    
  },
  //关闭
  closeBox(){
    var that=this;
    that.setData({
      is_send:0
    })
  },
  //解除检修
  maintenance_state_switching(){
    var that = this;
    var sn = that.data.device_no;
    app.showModal("","请先确认机器无漏水等情况再解除检修",function(){
      app.ajax({
        url: "House/Issue/maintenance_state_switching",
        data: { sn: sn, value: 0},
        success: function (res) {
          app.showToast(res.data.message+",请下拉刷新数据", 'none', 2500);
          that.syncRedisToDevice();
      
        }
      })
    })
  
  },
  //数据同步
  data_sync(){
    var that = this;
    var sn = that.data.device_no;
      app.ajax({
        url: "House/Issue/data_sync",
        data: { sn: sn, remaining_traffic: that.data.info.remaining_traffic,remaining_days:that.data.info.remaining_days,used_traffic:that.data.info.used_traffic,used_days:that.data.info.used_days},
        success: function (res) {
          app.showToast(res.data.message+",请下拉刷新数据", 'none', 2500);
          that.syncRedisToDevice();
        }
      })
  },
  //单个下发滤芯数据
  filter_element_reset_modification(e){
    var that = this;
    var value = e.currentTarget.dataset.remain_day;
    var index = e.currentTarget.dataset.index+1;
    var sn = that.data.device_no;
      app.ajax({
        url: "House/Issue/filter_element_reset_modification",
        data: { sn: sn, type: 2,key:index,value:value},
        success: function (res) {
          app.showToast(res.data.message+",请下拉刷新数据", 'none', 2500);
          that.syncRedisToDevice();
        }
      })
  },
  //获取最新状态
  syncRedisToDevice(){
    var that = this;
    var sn = that.data.device_no;
    app.ajax({
      url: "House/Issue/syncRedisToDevice",
      data: { sn: sn},
      success: function (res) {
       
      }
    })
  }
  
})